package com.weilun.filter;

import com.weilun.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行了");
        //将请求和响应强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        String path = request.getRequestURI();

        //2.判断是否是登录请求，如果路径中包含"/login"，则放行
        if (path.contains("/login")){
            filterChain.doFilter(request,response);
            return;
        }

        //3.获取请求头中的token
        String token = request.getHeader("token");

        //4.判断token是否非法，如果非法，则重定向到登录页面，返回错误信息(响应401状态码)
        if (token==null || token.equals("")){
            log.info("token为空，响应401");
            response.setStatus(401);
            return;
        }
        //5.如果不为空，则解析token，如果解析失败，则重定向到登录页面，返回错误信息(响应401状态码)
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("token解析失败，响应401");
            response.setStatus(401);
            return;
        }
        //6.如果解析成功，则放行
        log.info("token解析成功，放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
